package com.lzw.intercept;


import cn.hutool.core.util.StrUtil;
import com.lzw.contant.CodeContant;
import com.lzw.utils.ThreadLocalUtil;
import com.lzw.utils.TokenCryptoUtil;
import com.lzw.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.PrintWriter;

public class BaseIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //业务处理
        //校验token--不存在/校验无效,返回告警信息--拦截
        if(StrUtil.isEmpty(token) || !TokenCryptoUtil.validateToken(token)) {
            // token无效时返回详细的错误信息
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            R result = R.fail(CodeContant.VALIDATE_FAIL_CODE,"token无效或已过期");
            ObjectMapper mapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            writer.write(mapper.writeValueAsString(result));
            writer.flush();
            writer.close();
            return false;
        }
        //存在且有效--得到token中封装的内容,并存入ThreadLocal--放行
        String userId = TokenCryptoUtil.getUserIdFromToken(token);
        ThreadLocalUtil.set("id",userId);
        //新增内容,考虑到登出需要将之前的token无效化，所以TL也需要当前的 token信息,这里一般不会出现旧token,因为每个线程都是独一的
        String oldToken = ThreadLocalUtil.get("token");
        if(StrUtil.isEmpty(oldToken))
            ThreadLocalUtil.set("token",token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal中的数据
        ThreadLocalUtil.clear();
    }



}